/**
 * pillage_room_1
 */


Creep.prototype.registerPillage=function () {
    if(this.spawning){
        let flag = this.headTaskFlag();
        if(flag)flag.memory.spawnTime = Game.time
    }
};

Creep.prototype.pillage=function () {
    let flag = this.headTaskFlag()
    if(!flag)return;
    if(flag.pos.roomName!=this.pos.roomName||this.pos.isBorder()){
        if(!flag||this.ticksToLive<400){
            this.suicide();
        }
        this.goTo(flag);
        return;
    }
    if(this.store.getFreeCapacity(RESOURCE_ENERGY)==0){
        this.fillAll(this.mainRoom().storage)
    }
    let target = this.pos.findClosestByPath(FIND_STRUCTURES,{filter:e=>{
            return e.store&&e.store.getAllResTypeCount()&&e.structureType!=STRUCTURE_CONTAINER
        },ignoreCreeps:true});
    if(target){
        this.carryAll(target);
        this.execLastTask();
    }else{
        flag.remove();
        this.popTask();
        this.fillAll(this.mainRoom().storage)
        this.execLastTask();
    }
};

let pro = {
    getPillagerBodyConfig: function (energy){
        let current=0;
        let cost = BODYPART_COST[CARRY]+BODYPART_COST[MOVE];
        let num=0;
        while (current+cost<=energy){// 挖矿的不需要carry 直接 4：1 没问题的！ 体型越大越好
            num+=1;
            current+=cost
            if(num>=25)break;
        }
        return ManagerCreeps.calcBodyPart({ [CARRY]: num, [MOVE]: num });
    },
    exec:function (room) {
        if((Game.time+room.hashCode())%30!=0)return;
        if(!room.storage)return;
        room.flags("pillage").sort().forEach(flag=>{
            let pillager = room.creeps("pillager", false).filter(e => e.headTaskFlag()&&e.headTaskFlag().name == flag.name).head();
            if(pillager)return;
            let tasks = [UtilsTask.taskFlag(flag,  "pillage","registerPillage")]
            StationHive.trySpawn(room, room.name, pro.getPillagerBodyConfig(room.getEnergyCapacityAvailable()), "pillager", tasks)
        })
    }
}


global.StrategyPillage=pro;